#include "BDMessageManager.h"
#include "BDReceiver.h"
#include "BDSender.h"

BDMessageManager* BDMessageManager::m_pInstance = NULL;

BDMessageManager::BDMessageManager()
{
	m_mapSender.insert(std::pair<SenderType, BDSender*>(LIB_SENDER, new BDSender(LIB_SENDER_ADDRESS)));
	m_mapSender.insert(std::pair<SenderType, BDSender*>(UI_SENDER, new BDSender(UI_SENDER_ADDRESS)));

	m_mapReceiver.insert(std::pair<ReceiverType, BDReceiver*>(LIB_RECEIVER, new BDReceiver(UI_SENDER_ADDRESS)));
	m_mapReceiver.insert(std::pair<ReceiverType, BDReceiver*>(UI_RECEIVER, new BDReceiver(LIB_SENDER_ADDRESS)));
}


BDMessageManager::~BDMessageManager()
{
	std::map<ReceiverType, BDReceiver*>::iterator it1 = m_mapReceiver.begin();
	for (; it1 != m_mapReceiver.end(); ++it1) {
		delete it1->second;
		it1->second = NULL;
	}

	std::map<SenderType, BDSender*>::iterator it2 = m_mapSender.begin();
	for (; it2 != m_mapSender.end(); ++it2) {
		delete it2->second;
		it2->second = NULL;
	}
}

BDMessageManager* BDMessageManager::GetInstance()
{
	if (m_pInstance == NULL) {
		m_pInstance = new BDMessageManager;
	}
	return m_pInstance;
}

void BDMessageManager::Destroy()
{
	if (m_pInstance == NULL) {
		return;
	}
	delete m_pInstance;
	m_pInstance = NULL;
}

BDReceiver* BDMessageManager::GetReceiver(ReceiverType type)
{
	std::map<ReceiverType, BDReceiver*>::iterator it = m_mapReceiver.find(type);
	if (it == m_mapReceiver.end()) {
		return NULL;
	}
	return it->second;
}

BDSender* BDMessageManager::GetSender(SenderType type)
{
	std::map<SenderType, BDSender*>::iterator it = m_mapSender.find(type);
	if (it == m_mapSender.end()) {
		return NULL;
	}
	return it->second;
}

void BDMessageManager::Start()
{
	std::map<ReceiverType, BDReceiver*>::iterator it = m_mapReceiver.begin();
	for (; it != m_mapReceiver.end(); ++it) {
		BDReceiver* pReceiver = it->second;
		if (pReceiver == NULL) {
			continue;
		}
		pReceiver->Start();
	}
}

void BDMessageManager::Stop()
{
	std::map<ReceiverType, BDReceiver*>::iterator it = m_mapReceiver.begin();
	for (; it != m_mapReceiver.end(); ++it) {
		BDReceiver* pReceiver = it->second;
		if (pReceiver == NULL) {
			continue;
		}
		pReceiver->Stop();
		pReceiver->Wait();
	}
}